<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { axiosrmedical } from '../../http/axiosRead';
import { axioswmedical } from '../../http/axiosWrtie';
import { showToast, showDialog } from 'vant';

const router = useRouter();

const patientId = ref<number>(1);
const patientData = ref<any>(null);
const loading = ref<boolean>(false);
const selectedAmount = ref<number>(50);
const customAmount = ref<string>('');
const showCustomAmountInput = ref<boolean>(false);
const rechargeLoading = ref<boolean>(false);
const showConfirmDialog = ref(false);
const pendingAmount = ref(0);
const chongzhiList=ref({
   "patientId": 1,
    "doctorId": 0,
    "itemName": "余额充值",
    "amount": 1000,
    "isPaid": false,
    "createdTime": "2025-07-25T21:00:22.4671939+08:00",
    "orderNo": "RCH202507252100227341",
    "payTradeNo": null,
    "payType": "支付宝",
    "payStatus": "待支付",
    "payAmount": 1000,
    "refundAmount": null,
    "refundTradeNo": null,
    "refundStatus": null,
    "payTime": null,
    "refundTime": null,
    "payChannel": "手机网站支付",
    "notifyRaw": null,
    "createTime": "2025-07-25T21:00:22.467285+08:00",
    "updateTime": "2025-07-25T21:00:22.4673701+08:00",
    "id": 23,
    "isDeleted": false})


// 预设金额选项
const amountOptions = [50, 100, 200, 500, 1000];

// 获取患者信息
const fetchPatientData = async (id: number) => {
  loading.value = true;
  try {
    const response = await axiosrmedical.get('/Payment/GetPatientBalance', {
      headers: { 'axiosrmedical': true },
      params: { patientId: id }
    });
    
    if (response.data.code === 200) {
      patientData.value = response.data.data;
    } else {
      showToast(response.data.msg || '获取患者信息失败');
    }
  } catch (error) {
    console.error('请求出错:', error);
    showToast('获取患者信息失败');
  } finally {
    loading.value = false;
  }
};

// 选择充值金额
const selectAmount = (amount: number) => {
  selectedAmount.value = amount;
  showCustomAmountInput.value = false;
};

// 切换到自定义金额
const toggleCustomAmount = () => {
  showCustomAmountInput.value = true;
  customAmount.value = '';
};

// 获取实际充值金额
const getRechargeAmount = (): number => {
  if (showCustomAmountInput.value && customAmount.value) {
    return parseFloat(customAmount.value);
  }
  return selectedAmount.value;
};

// 充值
const confirmRecharge = async () => {
  const amount = getRechargeAmount();
  
  if (!amount || amount <= 0) {
    showToast('请输入有效的充值金额');
    return;
  }
  
  rechargeLoading.value = true;
  try {
    const rechargeParams = {
      patientId: patientId.value,
      amount: amount
    };
    
    const response = await axioswmedical.post('/Pay/RechargeBalance', rechargeParams, {
      headers: { 'axioswmedical': true }
    });
    
    if (response.data.code === 200 && response.data.data) {
      chongzhiList.value=response.data.data;
      // 弹出确认充值对话框
      pendingAmount.value = amount;
      // showConfirmDialog.value = true;


try {
    const response = await axioswmedical.post('/Alipay/WapPay', {
      outTradeNo: chongzhiList.value.orderNo.toString(),
      subject: chongzhiList.value.itemName,
      body: `${chongzhiList.value.patientId}在${chongzhiList.value.payType}的缴费`,
      totalAmount: chongzhiList.value.amount.toString(),
      notifyUrl: "http://101.201.170.32:5289/api/AlipayNotify/wappay",
      returnUrl: `${window.location.origin}/recharge-card?paymentId=${patientId.value}`
    });
    // 刷新余额
  fetchPatientData(patientId.value);
    
    document.write(response.data);
  } catch (error) {
    console.error('充值缴费支付失败:', error);
  }
      
    } else {
      showToast(response.data.msg || '充值请求失败');
    }
  } catch (error) {
    console.error('充值请求出错:', error);
    showToast('充值请求失败，请稍后再试');
  } finally {
    rechargeLoading.value = false;
  }
};

// const handleConfirmRecharge = async () => {
//   showConfirmDialog.value = false;
//   try {
//     const response = await axioswmedical.post('/Alipay/WapPay', {
//       outTradeNo: chongzhiList.value.orderNo.toString(),
//       subject: chongzhiList.value.itemName,
//       body: `${chongzhiList.value.patientId}在${chongzhiList.value.payType}的缴费`,
//       totalAmount: chongzhiList.value.amount.toString(),
//       notifyUrl: "http://101.201.170.32:5289/AlipayNotify/wappay",
//       returnUrl: `${window.location.origin}/recharge-card?paymentId=${patientId.value}`
//     });
//     // 刷新余额
//   fetchPatientData(patientId.value);
    
//     document.write(response.data);
//   } catch (error) {
//     console.error('充值缴费支付失败:', error);
//   }
// };

// 跳转到充值记录页面
const goToRechargeRecords = () => {
  router.push({
    path: '/recharge-records',
    query: { patientId: patientId.value }
  });
};

// 切换患者
const switchPatient = () => {
  router.push('/patient-select?from=recharge');
};

// 初始化
onMounted(() => {
  // 获取URL中的参数
  const urlParams = new URLSearchParams(window.location.search);
  const selectedPatientId = urlParams.get('selectedPatientId');
  
  if (selectedPatientId && !isNaN(Number(selectedPatientId))) {
    patientId.value = Number(selectedPatientId);
  }
  
  fetchPatientData(patientId.value);
});
</script>

<template>
  <div class="recharge-page">
    <div class="header">
      <van-nav-bar
        title="门诊充值"
        left-arrow
        @click-left="router.back()"
      />
    </div>
    
    <div class="content">
      <van-loading v-if="loading" vertical>加载中...</van-loading>
      
      <template v-else-if="patientData">
        <div class="patient-info-card">
          <div class="patient-info-header">
            <div class="patient-name">{{ patientData.patientName }}</div>
            <van-button size="small" plain type="primary" @click="switchPatient">切换患者</van-button>
          </div>
          
          <div class="patient-details">
            <div class="detail-item">
              <span class="label">身份证:</span>
              <span class="value">{{ patientData.idCard }}</span>
            </div>
            <div class="detail-item">
              <span class="label">手机号:</span>
              <span class="value">{{ patientData.phoneNumber }}</span>
            </div>
          </div>
        </div>
        
        <div class="balance-card">
          <div class="balance-title">卡内余额</div>
          <div class="balance-amount">¥{{ (patientData.currentBalance || 0).toFixed(2) }}</div>
        </div>
        
        <div class="recharge-section">
          <div class="section-title">在线充值</div>
          
          <div class="amount-options">
            <div 
              v-for="amount in amountOptions" 
              :key="amount"
              class="amount-option"
              :class="{ 'active': !showCustomAmountInput && selectedAmount === amount }"
              @click="selectAmount(amount)"
            >
              {{ amount }}
            </div>
            
            <div 
              class="amount-option"
              :class="{ 'active': showCustomAmountInput }"
              @click="toggleCustomAmount"
            >
              自定义
            </div>
          </div>
          
          <div v-if="showCustomAmountInput" class="custom-amount">
            <van-field
              v-model="customAmount"
              type="digit"
              placeholder="请输入充值金额"
              :border="false"
            />
          </div>
        </div>
        
        <div class="recharge-records">
          <div class="records-header">
            <div class="record-title">充值记录</div>
            <van-button 
              size="small"
              type="primary"
              plain
              class="record-btn"
              @click="goToRechargeRecords"
            >
              充值记录
            </van-button>
          </div>
        </div>
        
        <div class="action-buttons">
          <span style="color: cadetblue;">支持通过手机浏览器支付</span>
          <van-button
            type="primary"
            block
            :loading="rechargeLoading"
            loading-text="处理中..."
            @click="confirmRecharge"
          >
            确认充值
          </van-button>
        </div>
      </template>
      
      <div v-else class="no-data">
        <van-empty description="暂无数据" />
      </div>
    </div>
    <!-- <van-dialog
      v-model:show="showConfirmDialog"
      title="确认充值"
      show-cancel-button
      @confirm="handleConfirmRecharge"
      custom-class="custom-recharge-dialog"
      confirm-button-color="#1989fa"
      cancel-button-color="#666666"
    >
      <div class="dialog-content">
        <div class="dialog-item">患者姓名：<span class="dialog-value">{{ patientData?.patientName }}</span></div>
        <div class="dialog-item">卡内余额：<span class="dialog-value">¥{{ patientData.currentBalance?.toFixed(2) }}</span></div>
        <div class="dialog-item">充值金额：<span class="dialog-value">¥{{ pendingAmount.toFixed(2) }}</span></div>
      </div>
    </van-dialog> -->
  </div>
</template>

<style scoped>
.recharge-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  padding: 16px;
}

.patient-info-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.patient-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.patient-name {
  font-size: 18px;
  font-weight: 500;
}

.patient-details {
  color: #666;
}

.detail-item {
  margin-bottom: 8px;
  display: flex;
}

.label {
  min-width: 60px;
  color: #999;
}

.balance-card {
  background: linear-gradient(135deg, #1989fa, #39a9ed);
  color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 4px 8px rgba(25, 137, 250, 0.2);
}

.balance-title {
  font-size: 14px;
  margin-bottom: 8px;
}

.balance-amount {
  font-size: 28px;
  font-weight: 500;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin: 16px 0 8px;
}

.amount-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-top: 12px;
}

.amount-option {
  background-color: #f7f8fa;
  border-radius: 4px;
  padding: 12px 0;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
}

.amount-option.active {
  background-color: #e8f3ff;
  color: #1989fa;
  border: 1px solid #1989fa;
}

.custom-amount {
  margin-top: 16px;
  background-color: #fff;
  border-radius: 4px;
  padding: 4px 12px;
}

.recharge-records {
  margin-top: 20px;
}

.records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.record-title {
  font-size: 16px;
  font-weight: 500;
}

.record-btn {
  margin-left: 10px;
}

.action-buttons {
  margin-top: 24px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.payment-item-title {
  display: flex;
  justify-content: space-between;
  font-weight: 500;
}

.payment-amount {
  color: #1989fa;
}

.payment-item-details {
  display: flex;
  justify-content: space-between;
  color: #999;
  font-size: 12px;
}

.payment-date {
  color: #999;
}

/* 自定义充值弹窗样式 */
.custom-recharge-dialog {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.dialog-content {
  padding: 20px;
}

.dialog-item {
  margin-bottom: 12px;
  font-size: 15px;
  line-height: 1.5;
}

.dialog-value {
  color: #1989fa;
  font-weight: 500;
}

:deep(.van-dialog__title) {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  padding: 16px 20px 12px;
}

:deep(.van-dialog__content) {
  padding: 0 20px;
}

:deep(.van-dialog__footer) {
  padding: 12px 20px 16px;
  border-top: 1px solid #f5f5f5;
}
</style>